import { logger } from '../core/logger';
import { showPopup } from '../core/utils';
import emitter from '@ohos.events.emitter';
import { globalData } from '../core/globalData';
import { ajaxResult } from '../models/ajaxResult';
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from '@ohos/axios';

export const HOST = "https://dovetm.top/sas/";
export abstract class clientBase {
  constructor() {
    axios.interceptors.response.use((response: AxiosResponse) => {
      return response;
    }, (err: AxiosError) => {
      if (err.code == 'ECONNABORTED') {
        showPopup('请求超时或者断开！');
        emitter.emit({
          eventId: 1
        })
      }
      logger.instance.error(err);
      return Promise.reject(err);
    });
  }

  get withToken() {
    const config: AxiosRequestConfig = {
      headers: { Authorization: `Bearer ${globalData.clientToken}` }
    };
    return config;
  }

  buildSuccessResult<T>(data?: T, msg?: string): ajaxResult<T> {
    let r = new ajaxResult<T>();
    r.success = true;
    r.message = msg;
    r.result = data;
    return r;
  }

  buildFailedResult<T>(msg?: string): ajaxResult<T> {
    let r = new ajaxResult<T>();
    if (msg)
      r.message = msg;
    r.success = false;
    return r;
  }

  buildExceptionResult<T>(exc: Error): ajaxResult<T> {
    let r = new ajaxResult<T>();
    r.message = exc.message;
    r.success = false;
    return r;
  }
}